package com.itheima.app.manager.testSoul;

import cn.hutool.core.collection.CollUtil;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.testSoul.*;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.db.testSoul.*;
import com.itheima.vo.testSoulVo.*;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class TestSoulManager {
    
    @DubboReference
    private QuestionnaireService questionnaireService;
    
    @DubboReference
    private QuestionsService questionsService;
    
    @DubboReference
    private OptionsService optionsService;

    @DubboReference
    private ReportService reportService;

    @DubboReference
    private DimensionsService dimensionsService;

    @DubboReference
    private UserInfoService userInfoService;

    @DubboReference
    private QuestionnairelockService questionnairelockService;
    
    //获取灵魂问卷列表
    public List<QuestionnaireVo> testSoul() {
        Long userId = UserHolder.get().getId();
        //获取所有的问卷
        List<QuestionnaireVo> list = questionnaireService.findAll();
        //获取该用户的所有问卷锁
        Map<String , Integer> map = questionnairelockService.findByUserId(userId);
        //如果用户不存在问卷锁,创建3个问卷的锁到数据库
        if(map.size()==0){
            for (QuestionnaireVo vo : list) {
                Questionnairelock lock = new Questionnairelock();
                lock.setQuestionnaireId(Long.valueOf(vo.getId()));
                lock.setUserId(userId);
                if (vo.getId().equals("1")) {
                    lock.setIsLock(0);
                }else {
                    lock.setIsLock(1);
                }
                questionnairelockService.save(lock);
            }
        }
        //保存完后重新获取
        map = questionnairelockService.findByUserId(userId);
        //获取每个问卷的问题
        Map<String, List<QuestionsVo>> mapQuestion = questionsService.findAll();
        //获取所有问题的答案
        Map<String, List<OptionsVo>> mapOption = optionsService.findAll();
        //获取用户所有的report
        Map<String , Report> mapReport = reportService.findByUserId(userId);
        //装载数据
        for (QuestionnaireVo questionnaire : list) {
            //获取问卷id
            String id = questionnaire.getId();
            //从mapQuestion获取其问题
            List<QuestionsVo> questions = mapQuestion.get(id);
            questionnaire.setQuestions(questions);
            //设置lock值
            Integer integer = map.get(id);
            questionnaire.setIsLock(integer);
            //设置reprotId
            //先判断map中是否有key，有设置，没有不设置
            if (mapReport.containsKey(questionnaire.getId())){
                questionnaire.setReportId(mapReport.get(questionnaire.getId()).getId().toString());
            }
            for (QuestionsVo question : questions) {
                //获取问题id
                String questionId = question.getId();
                //从mapOption获取其选项
                List<OptionsVo> options = mapOption.get(questionId);
                question.setOptions(options);
            }
        }
        return list;
    }

    //提交灵魂问卷答案
    public String commit(List<Answers> list) {
        //获取问题ids和答案ids
        List<Long> questionIds = CollUtil.getFieldValues(list, "questionId", Long.class);
        List<Long> optionIds = CollUtil.getFieldValues(list, "optionId", Long.class);
        Report report = new Report();
        //计算总分
        Integer score = optionsService.findSumScoreByIds(optionIds);
        //Integer score = 10;
        report.setScore(score);
        //获取性格和结论和维度
        Report result = getCharacter(score,report);
        //获取问题
        List<Questions> questionsList = questionsService.findByIds(questionIds);
        //获取问卷的id
        Questions questions = questionsList.get(0);
        Long questionnaireId = questions.getQuestionnaireId();
        result.setQuestionnaireId(questionnaireId);
        //获取userid
        Long userId = UserHolder.get().getId();
        result.setUserId(userId);
        //先查询是否存在当前的报告
        Report report1 = reportService.findById(userId,questionnaireId);
        //设置cover 后期完善先写死
        result.setCover(null);
        if (report1 == null){
            //返回一个设置好id的reprot
            result = reportService.save(report);
        }else {
            result.setId(report1.getId());
            reportService.update(result);
        }
        Long reportId = result.getId();
        //更新下一级的问卷
        //判断当前问卷id
        if (questionnaireId != 3){
            Questionnairelock lock = new Questionnairelock();
            lock.setQuestionnaireId(questionnaireId + 1);
            lock.setUserId(userId);
            lock.setIsLock(0);
            //更新关系表
            questionnairelockService.updateByUserId(lock);
        }
        //设置维度数据
        List<Dimensions> dimensions = getDimensions(score, reportId);
        dimensionsService.save(dimensions);
        return reportId.toString();
    }

    //获取人格类型及鉴定结果和维度属性
    public Report getCharacter(Integer score,Report report){
        if (score <= 21) {
            report.setCharacterResult("猫头鹰");
            report.setConclusion("他们的共同特质为重计划、条理、细节精准。在行为上，表现出喜欢理性思考与分析、较重视制度、结构、规范。他们注重执行游戏规则、循规蹈矩、巨细靡遗、重视品质、敬业负责");
        } else if (score > 21 && score <= 40) {
            report.setCharacterResult("白兔型");
            report.setConclusion("平易近人、敦厚可靠、避免冲突与不具批判性。在行为上，表现出不慌不忙、冷静自持的态度。他们注重稳定与中长程规划，现实生活中，常会反思自省并以和谐为中心，即使面对困境，亦能泰然自若，从容应付");
        }else if (score > 40 && score <= 55) {
            report.setCharacterResult("狐狸型");
            report.setConclusion("人际关系能力极强，擅长以口语表达感受而引起共鸣，很会激励并带动气氛。他们喜欢跟别人互动，重视群体的归属感，基本上是比较「人际导向」。由于他们富同理心并乐于分享，具有很好的亲和力，在服务业、销售业、传播业及公共关系等领域中，狐狸型的领导者都有很杰出的表现。");}
        else {
            report.setCharacterResult("狮子型");
            report.setConclusion("性格为充满自信、竞争心强、主动且企图心强烈，是个有决断力的领导者。一般而言，狮子型的人胸怀大志，勇于冒险，看问题能够直指核心，并对目标全力以赴。\n" +
                    "他们在领导风格及决策上，强调权威与果断，擅长危机处理，此种性格最适合开创性与改革性的工作。");
        }
        return report;
    }
    //获取维度属性
    public List<Dimensions> getDimensions(Integer score,Long reportId){
        List<Dimensions> list = new ArrayList<>();
        Dimensions dimension1 = new Dimensions();
        Dimensions dimension2 = new Dimensions();
        Dimensions dimension3 = new Dimensions();
        Dimensions dimension4 = new Dimensions();
        dimension1.setReportId(reportId);
        dimension1.setDimensionality("外向");
        dimension2.setReportId(reportId);
        dimension2.setDimensionality("判断");
        dimension3.setReportId(reportId);
        dimension3.setDimensionality("抽象");
        dimension4.setReportId(reportId);
        dimension4.setDimensionality("理性");
        if (score >= 0 && score <= 10){
            dimension1.setDimensionalityValue("10%");
            dimension2.setDimensionalityValue("10%");
            dimension3.setDimensionalityValue("10%");
            dimension4.setDimensionalityValue("10%");
        }else {
            dimension1.setDimensionalityValue("20%");
            dimension2.setDimensionalityValue("20%");
            dimension3.setDimensionalityValue("20%");
            dimension4.setDimensionalityValue("20%");
        }
        list.add(dimension1);
        list.add(dimension2);
        list.add(dimension3);
        list.add(dimension4);
        return list;
    }
    //通过reportid获取report
    public ReportVo getReport(Long id) {
        //首先获取ReportVo
        Report report = reportService.findOne(id);
        ReportVo vo = ReportVo.inint(report);
        //查询dimensions
        List<DimensionsVo> dimensionsVos = dimensionsService.findByReportId(id);
        //查询用户信息
        UserInfo userInfo = userInfoService.findById(UserHolder.get().getId());
        //推荐用户,通过character_result进行查询
        List<Report> similarReport = reportService.findSimilar(Long.valueOf(report.getId().toString()));
        //提取similarReport中的userId
        List<Long> userIds = CollUtil.getFieldValues(similarReport, "userId", Long.class);
        //通过userIds进行查找用户信息
        Map<Long, UserInfo> byIds = userInfoService.findByIds(userIds);
        List<SimilarYouVo> similarYouVos = userInfoService.findByIdsVo(userIds,UserHolder.get().getId());
        //组装数据
        vo.setDimensions(dimensionsVos);
        vo.setSimilarYou(similarYouVos);
        vo.setId(userInfo.getId().intValue());
        vo.setAvatar(userInfo.getAvatar());
        return vo;
    }
}
